package com.zhanghe.security.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

public class ResponseUtil {

    public static void writeResponse(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse, String content,String origins) throws IOException {
        String originHeader = httpServletRequest.getHeader("Origin");
        setOrigins(httpServletResponse,origins,originHeader);
        httpServletResponse.setContentType("application/json");
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        httpServletResponse.getOutputStream().write(content.getBytes());
    }
    public static void writeResponse(HttpServletResponse httpServletResponse, String content) throws IOException {
        httpServletResponse.setContentType("application/json");
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        httpServletResponse.getOutputStream().write(content.getBytes());
    }

    public static void setOrigins(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String origins) throws IOException {
        String originHeader = httpServletRequest.getHeader("Origin");
        setOrigins(httpServletResponse,origins,originHeader);
    }

    public static void setOrigins(HttpServletResponse httpServletResponse,String origins,String originHeader){
        String[] origin = origins.split(",");
        if(origin!=null && Arrays.asList(origin).contains(originHeader)){
            httpServletResponse.setHeader("Access-Control-Allow-Origin", originHeader);
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpServletResponse.setHeader("Access-Control-Allow-Headers", "token,Content-Type,refresh-token,access-token");
        }
    }
}
